package com.iraeta.api;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iraeta.WeiXinConfig;
import com.iraeta.common.ServiceException;
import com.iraeta.entity.main.WeiXinLiZhi;
import com.iraeta.entity.main.WeiXinUser;
import com.iraeta.service.hik.IWeiXinLiZhiService;
import com.iraeta.service.hik.IWeiXinUserService;
import com.iraeta.uitl.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service(value = "weiXinApi")
public class WeiXinApi {
    private static final Logger logger = LoggerFactory.getLogger(WeiXinApi.class);

    @Autowired
    WeiXinConfig weiXinConfig;
    @Autowired
    private IWeiXinUserService weiXinUserService;
    @Autowired
    private IWeiXinLiZhiService weiXinLiZhiService;

    private String access_token = null;
    private Date tokenExpireTime = null;

    public String getAccess_token() {
        if (null == access_token || new Date().getTime() > tokenExpireTime.getTime()) {
            return getAccessToken();
        } else {
            return access_token;
        }
    }
    private String getAccessToken(){
        String corpid = weiXinConfig.getCompId();   //企业id
        String secret = weiXinConfig.getAppSecret();
        try {
            String res = HttpUtils.sendGet("https://qyapi.weixin.qq.com/cgi-bin/gettoken", "corpid="+corpid+"&corpsecret="+secret);
            JSONObject jsonObject = JSON.parseObject(res);
            Object accesstoken = jsonObject.get("access_token");
            if (null != accesstoken) {
                access_token = accesstoken.toString();
                tokenExpireTime = DateUtil.offsetMinute(new Date(), 30);
            }
        } catch (Exception e) {
            e.printStackTrace();
            cleanTokenCache();
            throw new ServiceException("微信token获取失败");
        }
        return access_token;
    }
    private void cleanTokenCache() {
        access_token = null;
        tokenExpireTime = null;
    }

    private List<String> getAllDeptId(){
        String token = this.getAccess_token();
        List<String> deptIdList = new ArrayList<>();
        try {
            String res = HttpUtils.sendGet("https://qyapi.weixin.qq.com/cgi-bin/department/simplelist", "access_token="+token);
            JSONObject jsonObject = JSON.parseObject(res);
            if(jsonObject.getIntValue("errcode") != 0){
                throw new RuntimeException("获取企业部门Id列表失败" + jsonObject.getString("errmsg"));
            }
            JSONArray deptJSONArray = jsonObject.getJSONArray("department_id");
            for(int i=0; i<deptJSONArray.size();i++){
                JSONObject deptJSONObject = deptJSONArray.getJSONObject(i);
                String id = deptJSONObject.getString("id");
                deptIdList.add(id);
            }
        } catch (Exception e) {
            throw new ServiceException("获取企业部门Id列表失败" + e.getMessage());
        }
        return deptIdList;
    }

    private List<WeiXinUser> getDeptUser(String deptId){
        String token = this.getAccess_token();
        List<WeiXinUser> weiXinUserList = new ArrayList<>();
        try {
            String res = HttpUtils.sendGet("https://qyapi.weixin.qq.com/cgi-bin/user/list", "access_token="+token+"&department_id="+deptId);
            JSONObject jsonObject = JSON.parseObject(res);
            if(jsonObject.getIntValue("errcode") != 0){
                throw new RuntimeException("获取部门用户列表失败" + jsonObject.getString("errmsg"));
            }
            JSONArray userJSONArray = jsonObject.getJSONArray("userlist");
            for(int i=0; i<userJSONArray.size();i++){
                JSONObject userJSONObject = userJSONArray.getJSONObject(i);
                WeiXinUser weiXinUser = new WeiXinUser();
                weiXinUser.setUserid(userJSONObject.getString("userid"));
                weiXinUser.setName(userJSONObject.getString("name"));
                weiXinUser.setMobile(userJSONObject.getString("mobile"));
                weiXinUserList.add(weiXinUser);
            }
        } catch (Exception e) {
            throw new ServiceException("获取部门用户列表失败" + e.getMessage());
        }
        return weiXinUserList;
    }

    private List<WeiXinUser> getAllUser(){
        List<String> deptIds = this.getAllDeptId();
        List<WeiXinUser> weiXinUserList = new ArrayList<>();
        for (String deptId : deptIds) {
            List<WeiXinUser> deptUsers = this.getDeptUser(deptId);
            try {
                Thread.sleep(100L);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            weiXinUserList.addAll(deptUsers);
        }
        return weiXinUserList;
    }

    public void autoGetWeiXinData(){
        logger.info("autoGetWeiXinData调用");
        try {
            List<WeiXinUser> weiXinUserList = this.getAllUser();    //这是最新的网络数据
            for (WeiXinUser weiXinUser : weiXinUserList) {
                try {
                    weiXinUser.setCreateTime(new Date());
                    weiXinUserService.insertWeiXinUser(weiXinUser);     //新员工新增到database中
                }catch (Exception e){}
            }

            List<WeiXinUser> dbWeiXinUserList = weiXinUserService.selectWeiXinUserList(new WeiXinUser());   //这是历史数据
            List<WeiXinUser> liZhiUserList = dbWeiXinUserList.stream().filter(x->{
                return weiXinUserList.stream().noneMatch(n->n.getUserid().equals(x.getUserid()));
            }).collect(Collectors.toList());

            for (WeiXinUser liZhiUser : liZhiUserList) {
                try {
                    WeiXinLiZhi weiXinLiZhi = new WeiXinLiZhi();
                    weiXinLiZhi.setUserid(liZhiUser.getUserid());
                    weiXinLiZhi.setName(liZhiUser.getName());
                    weiXinLiZhi.setMobile(liZhiUser.getMobile());
                    weiXinLiZhi.setCreateTime(liZhiUser.getCreateTime());
                    weiXinLiZhiService.insertWeiXinLiZhi(weiXinLiZhi);
                }catch (Exception e){}
                weiXinUserService.deleteWeiXinUserById(liZhiUser.getId());
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("autoGetWeiXinData调用异常" + e.getMessage());
        }
    }

    /*测试离职员工的比对
    public static void main(String[] args) {
        List<WeiXinUser> weiXinUserList = new ArrayList<>();
        WeiXinUser weiXinUser1 = new WeiXinUser();
        weiXinUser1.setUserid("u1");
        WeiXinUser weiXinUser2 = new WeiXinUser();
        weiXinUser2.setUserid("u2");
        weiXinUserList.add(weiXinUser1);
        weiXinUserList.add(weiXinUser2);

        List<WeiXinUser> dbWeiXinUserList = new ArrayList<>();
        dbWeiXinUserList.add(weiXinUser1);
        dbWeiXinUserList.add(weiXinUser2);
        WeiXinUser weiXinUser3 = new WeiXinUser();
        weiXinUser3.setUserid("u3");
        WeiXinUser weiXinUser4 = new WeiXinUser();
        weiXinUser4.setUserid("u4");
        dbWeiXinUserList.add(weiXinUser3);
        dbWeiXinUserList.add(weiXinUser4);

        List<WeiXinUser> liZhiUserList = dbWeiXinUserList.stream().filter(x->{
            return weiXinUserList.stream().noneMatch(n->n.getUserid().equals(x.getUserid()));
        }).collect(Collectors.toList());
        System.out.println(liZhiUserList);
    }
     */
}
